<?php

class QuestaoController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
                    array(
                        'allow',
                        'actions'=>array('index','create','update','admin','delete'),
                        'expression'=>'Yii::app()->user->isAdmin',
                    ),
                    array(
                        'deny',
                        'users'=>array('*'),
                    ),
		);
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'admin' page.
	 */
	public function actionCreate($q)
	{
            $model = new Questao;
            $model->id_questionario = $q;
            
            $eixoQuestao = new EixoQuestao;
            
            $eixosQuestionario = QuestionarioEixo::model()->findAll('id_questionario = :q',array(':q'=>$q));
            $questionario = Questionario::model()->findByPk($q);
            
            $valid = false;
            
            if(isset($_POST['Questao']))
            {
                $model->attributes = $_POST['Questao'];
                $valid = $model->validate();
                
                if($valid)
                    $model->save(false);
            }
            
            if(isset($_POST['EixoQuestao']))
            {
                foreach($eixosQuestionario as $eixo)
                {
                    $eixoQuestao->attributes = $_POST['EixoQuestao'][$eixo->id_eixo];
                    $eixoQuestao->id_questao = $model->getPrimaryKey();
                    
                    $valid = $valid && $eixoQuestao->validate();                    
                }
                
                if($valid)
                {
                    foreach($eixosQuestionario as $eixo)
                    {
                        $eixoQuestao = new EixoQuestao;
                        $eixoQuestao->attributes = $_POST['EixoQuestao'][$eixo->id_eixo];
                        $eixoQuestao->id_questao = $model->getPrimaryKey();
                        $eixoQuestao->save(false);
                    }

                    Yii::app()->user->setFlash('sucesso','Questão cadastrada com sucesso!');
                    $this->redirect(array('admin/questao/admin','q'=>$q));
                }else
                {
                    Questao::model()->deleteByPk($model->getPrimaryKey());
                }
            }
                        
            $this->render('create',array(
                'model'=>$model,
                'questionario'=>$questionario,
                'eixosQuestionario'=>$eixosQuestionario,
                'eixoQuestao'=>$eixoQuestao,
            ));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($q,$id)
	{
		$model = $this->loadModel($id);
                $questionario = Questionario::model()->findByPk($q);
                $eixosQuestao = EixoQuestao::model()->findAll('id_questao = :id_questao',array(':id_questao'=>$id));

		if(isset($_POST['Questao']))
		{
			$model->attributes=$_POST['Questao'];
			if($model->save())
				$this->redirect(array('admin','q'=>$q));
		}

		$this->render('update',array(
			'model'=>$model,
                        'questionario'=>$questionario,
                        'eixosQuestao'=>$eixosQuestao,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
            if(Yii::app()->request->isPostRequest)
            {
                // we only allow deletion via POST request
                Alternativa::model()->deleteAll('id_questao = :id_questao',array(':id_questao'=>$id));
                EixoQuestao::model()->deleteAll('id_questao = :id_questao',array(':id_questao'=>$id));
                Questao::model()->deleteAll('id_questao = :id_questao',array(':id_questao'=>$id));

                // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
                if(!isset($_GET['ajax']))
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            }
            else
                throw new CHttpException(400,'Requisição Inválida.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($q)
	{
            $this->redirect(array('admin','q'=>$q));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin($q)
	{
		$model=new Questao('search');
		$model->unsetAttributes();
                $model->id_questionario = $q;
                //$model->pagination->pageSize= 100;
                
                $questionario = Questionario::model()->findByPk($q);
                
		$this->render('admin',array(
			'model'=>$model,
                        'questionario'=>$questionario,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Questao::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
            if(isset($_POST['ajax']) && $_POST['ajax']==='questao-form')
            {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }
	}        
}
